package com.wanpinghui.supplier.user.company;

import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.TextView;

import com.malinskiy.superrecyclerview.OnMoreListener;
import com.malinskiy.superrecyclerview.SuperRecyclerView;
import com.wanpinghui.supplier.R;
import com.wanpinghui.supplier.addrbook.StrangerInfoActivity;
import com.wanpinghui.supplier.common.BaseActivity;
import com.wanpinghui.supplier.user.UpdateUserInfoActivity;
import com.wanpinghui.supplier.user.company.adapter.AutoCompleteAdapter;
import com.wanpinghui.supplier.user.company.adapter.CompanyNameAdapter;
import com.wanpinghui.supplier.widgets.TitlePanelLayoutUser;
import com.wanpinghui.wphlibrary.WPHSdk;
import com.wanpinghui.wphlibrary.common.dialog.BaseDialogManager;
import com.wanpinghui.wphlibrary.common.dialog.YunBaseDialog;
import com.wanpinghui.wphlibrary.common.toast.ToastManager;
import com.wanpinghui.wphlibrary.model.business.BusinessService;
import com.wanpinghui.wphlibrary.model.oauth.UserInfoUtil;
import com.wanpinghui.wphlibrary.model.oauth.bean.UserBean;
import com.wanpinghui.wphlibrary.model.oauth.bean.UserInformation;
import com.wanpinghui.wphlibrary.model.order.OrderService;
import com.wanpinghui.wphlibrary.model.order.bean.OrderItemBean;
import com.wanpinghui.wphlibrary.model.order.bean.PageDataBean;
import com.wanpinghui.wphlibrary.model.user.UserInfoService;
import com.wanpinghui.wphlibrary.model.user.bean.CompanyBean;
import com.wanpinghui.wphlibrary.widgets.ThrottleButton;
import com.yunshl.yunshllibrary.recyclerview.BaseRecyclerViewAdapter;
import com.yunshl.yunshllibrary.recyclerview.OnItemClickListener;
import com.yunshl.yunshllibrary.utils.TextUtil;
import com.yunshl.yunshllibrary.view.YunShlEditText;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.List;

import retrofit.callback.YRequestCallback;

import static com.yunshl.yunshllibrary.recyclerview.BaseRecyclerViewAdapter.TYPE_PULL_MORE;

/**
 * Created by tg596 on 2018/1/23.
 */

@ContentView(R.layout.layout_activity_company_name)
public class CompanyNameActivity extends BaseActivity {

    @ViewInject(R.id.recyclerview)
    private SuperRecyclerView recyclerview;

    private CompanyNameAdapter companyNameAdapter;

    private ArrayList<String> listArray;
    private TitlePanelLayoutUser mTplTitle;
    /**
     * 输入完整的公司名称
     */
    private YunShlEditText mEdtCompanyName;

    private ThrottleButton btn_next;
    private static final int MAX_ONCE_MATCHED_ITEM = 5;                 // 提示框最多要显示的记录行数
    private static int prevCount = -1;                                  // 上一次记录行数
    private static int curCount = -1;                                   // 当前记录行数

    private int currpage = 1;

    private List<CompanyBean> companyBeanList;
    private CompanyBean bean;
    private TextView tv_warning_text;
    private String key_;

    @Override
    public String getName() {
        return null;
    }

    @Override
    public boolean isBar() {
        return false;
    }

    @Override
    public void initViews() {
        mTplTitle = (TitlePanelLayoutUser) findViewById(R.id.tpl_title);
        mEdtCompanyName = (YunShlEditText) findViewById(R.id.edt_company_name);
        btn_next = (ThrottleButton)findViewById(R.id.btn_next);
        tv_warning_text = (TextView)findViewById(R.id.tv_warning_text);
    }

    @Override
    public void bindEvents() {
        mTplTitle.setOnClickBacktrack(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        btn_next.setOnThrottleClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtil.isEmpty(mEdtCompanyName.getText().toString())){
                    showWarningText("请输入公司名称");
                    return;
                }
                final CompanyBean companyBean = new CompanyBean();
                if (bean != null){
                    companyBean.setId(bean.getId());
                }
                companyBean.setCompany_name(mEdtCompanyName.getTextString());
                WPHSdk.getService(UserInfoService.class)
                        .saveCompanyName(companyBean, new YRequestCallback<CompanyBean>() {
                            @Override
                            public void onSuccess(CompanyBean var1) {
                                Intent intent = new Intent(CompanyNameActivity.this, BusinessInformationActivity.class);
                                if (bean != null){
                                    intent.putExtra("bean",bean);
                                }
                                intent.putExtra("name",mEdtCompanyName.getTextString());
                                startActivity(intent);
                            }

                            @Override
                            public void onFailed(int var1, String message) {
                                showWarningText(message);
                            }

                            @Override
                            public void onException(Throwable var1) {

                            }
                        });
            }
        });
        initialize();
        companyNameAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, final int position) {
               View view1 = LayoutInflater.from(CompanyNameActivity.this).inflate(R.layout.view_dialog_join, null);
                final Button button = (Button) view1.findViewById(R.id.btn_right);
                final Button btn_left = (Button) view1.findViewById(R.id.btn_left);
                final YunBaseDialog dialog = BaseDialogManager.getInstance().getBuilder(CompanyNameActivity.this).setContentView(view1).create();
                button.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });
                btn_left.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        WPHSdk.getService(UserInfoService.class)
                                .joinCompany(companyNameAdapter.getDatas().get(position).getId(), new YRequestCallback<CompanyBean>() {
                                    @Override
                                    public void onSuccess(CompanyBean var1) {
                                        Intent intent = new Intent(CompanyNameActivity.this, CompanyInfoEditActivity.class);
                                        intent.putExtra("bean",var1);
                                        startActivity(intent);
                                        dialog.dismiss();
                                    }

                                    @Override
                                    public void onFailed(int var1, String message) {
                                        showWarningText(message);
                                        dialog.dismiss();
                                    }

                                    @Override
                                    public void onException(Throwable var1) {
                                        dialog.dismiss();
                                    }
                                });


                    }
                });
                dialog.show();
            }
        });
    }

    private void initialize(){
        recyclerview.setLayoutManager(new LinearLayoutManager(this));
        companyNameAdapter = new CompanyNameAdapter(this);
        recyclerview.setAdapter(companyNameAdapter);

        mEdtCompanyName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
//                Log.d(TAG, "onTextChanged: "+charSequence.toString());
                currpage= 1;
                key_ = charSequence.toString();
                if (TextUtil.isNotEmpty(key_)){
                    recyclerview.setVisibility(View.VISIBLE);
                    searchCompanyList(charSequence.toString(),currpage,BaseRecyclerViewAdapter.TYPE_PULL_REFRESH);
                }else {
                    recyclerview.setVisibility(View.INVISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        if (getIntent().getBooleanExtra("edit",false)){
            WPHSdk.getService(UserInfoService.class)
                    .getMyDraftsCompany(new YRequestCallback<CompanyBean>() {
                        @Override
                        public void onSuccess(CompanyBean var1) {
                            bean = var1;
                            bean.setId(getIntent().getLongExtra("id",0));
                            if (bean.getAudit_status() == 21 ) {
                                tv_warning_text.setVisibility(View.VISIBLE);
                                tv_warning_text.setText(bean.getRemark());
                            }
                            mEdtCompanyName.setText(var1.getCompany_name());
                        }

                        @Override
                        public void onFailed(int var1, String message) {
                            showWarningText(message);
                        }

                        @Override
                        public void onException(Throwable var1) {

                        }
                    });
        }


//        listArray=new ArrayList<>();
//        listArray.add("河南晶佳科技有限公司");
//        listArray.add("深圳市洲明科技有限公司");
//        listArray.add("深圳市云上科技有限公司");
//        listArray.add("深圳市蓝普科技有限公司");
//        listArray.add("深圳市xx科技有限公司");
//        listArray.add("深圳市hh科技有限公司");
//        listArray.add("广州市hh科技有限公司");
//        listArray.add("北京市hh科技有限公司");
//
////        AutoCompleteAdapter1 adapter1 = new AutoCompleteAdapter1(this);
////        adapter1.setDatas(listArray);
////        AutoCompleteAdapter autocompleteAdapter = new AutoCompleteAdapter(this,R.layout.item_auto_company_name,listArray);
////        mEdtCompanyName.setAdapter(autocompleteAdapter);
//        AutoCompleteAdapter   mCustomAdapter = new AutoCompleteAdapter(this, listArray);
//        mCustomAdapter.setDefaultMode(AutoCompleteAdapter.MODE_STARTSWITH | AutoCompleteAdapter.MODE_SPLIT);    // 设置匹配模式
//        mCustomAdapter.setSupportPreview(true);     // 支持使用特殊符号进行预览提示内容，默认为"@"

//        simpleItemHeight = mCustomAdapter.getSimpleItemHeight();
//        Toast.makeText(this, "simpleItemHeight: " + simpleItemHeight, Toast.LENGTH_SHORT).show(); // 103

//        mCustomAdapter.setOnFilterResultsListener(new AutoCompleteAdapter.OnFilterResultsListener() {
//            @Override
//            public void onFilterResultsListener(int count) {
//                curCount = count;
////                if (count > MAX_ONCE_MATCHED_ITEM) {        // 限制提示框最多要显示的记录行数
////                    curCount = MAX_ONCE_MATCHED_ITEM;
////                }
//                if (curCount != prevCount) {                // 仅当目前的数目和之前的不同才重新设置下拉框高度，避免重复设置
//                    prevCount = curCount;
//                   // mEdtCompanyName.setDropDownHeight(simpleItemHeight * curCount);
//                }
//            }
//        });

//        mCustomAdapter.setOnSimpleItemDeletedListener(new AutoCompleteAdapter.OnSimpleItemDeletedListener() {
//            @Override
//            public void onSimpleItemDeletedListener(String value) {
//                String old_history = getHistoryFromSharedPreferences(SP_KEY_CUSTOM);    // 获取之前的记录
//                String new_history = old_history.replace(value + SP_SEPARATOR, "");     // 用空字符串替换掉要删除的记录
//                saveHistoryToSharedPreferences(SP_KEY_CUSTOM, new_history);             // 保存修改过的记录
//            }
//        });

//        mEdtCompanyName.setAdapter(mCustomAdapter);       //
//        mEdtCompanyName.setThreshold(1);                  //
    }

    private boolean isContains(List<CompanyBean> companyBeanList){
        for (CompanyBean bean : companyBeanList){
            if (!bean.getCompany_name().contains(key_.toLowerCase())){
                return false;
            }
        }
        return true;
    }

    private void searchCompanyList(final String keyword_, int page, final int type) {
        WPHSdk.getService(UserInfoService.class).searchCompanyList( keyword_,page, new YRequestCallback<PageDataBean<CompanyBean>>() {
            @Override
            public void onSuccess(final PageDataBean var1) {
                if (type == BaseRecyclerViewAdapter.TYPE_PULL_REFRESH) {
                    companyBeanList = var1.getPdList();
                    if (companyBeanList != null && companyBeanList.size()>0){
                        if (!isContains(companyBeanList)){
                         //   ToastManager.getInstance().showToast("meiyou");
                            return;
                        } else {
                      //      ToastManager.getInstance().showToast("haha");
                        }
//                        if (companyBeanList.contains(key_)){
//
//                        }
                    }else {
                        companyBeanList.clear();
                        companyNameAdapter.notifyDataSetChanged();
                    }
                } else {
                    companyBeanList.addAll(var1.getPdList());
                }
                companyNameAdapter.setDatas(companyBeanList);
                if (companyNameAdapter.getDatas().size() < var1.getTotalResult()) {
                    recyclerview.setupMoreListener(new OnMoreListener() {
                        @Override
                        public void onMoreAsked(int overallItemsCount, int itemsBeforeMore, int maxLastVisiblePosition) {
                            recyclerview.showMoreProgress();
                            currpage = currpage + 1;
                            searchCompanyList(keyword_,currpage, TYPE_PULL_MORE);
                        }
                    }, 1);
                } else {
                    recyclerview.hideMoreProgress();
                    recyclerview.removeMoreListener();
                }

            }

            @Override
            public void onFailed(int var1, String message) {
                showWarningText(message);
            }

            @Override
            public void onException(Throwable var1) {
                var1.printStackTrace();

            }
        });
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();

    }

    @Override
    public void initData() {
//        mTplTitle.showRightText();
//        mTplTitle.setRightText("完成");


    }

}
